package user

import (
	"bytes"
	"cross-shard-channel/common"
	"cross-shard-channel/ledger"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func CallLedgerTransactionExe(tx common.Transaction, txName string) bool{
	// 初始化基本参数
	var requestObject ledger.TxEXE
	var responseObject ledger.TxEXEResponse
	client := &http.Client{};
	name := "/TxEXE"

	requestObject.Tx = tx
	requestObject.Name = txName

	// generate request body
	bodyStr,err := json.Marshal(requestObject)
	if err != nil {
		println(err.Error())
		return  false
	}
	bodyBuffer := bytes.NewBuffer(bodyStr)
	// do request
	url := ledger.LedgerIP + name
	request, _ := http.NewRequest("POST", url, bodyBuffer)
	request.Header.Set("Content-type", "application/json")
	response, err := client.Do(request)
	// error process
	if err != nil {
		println(err.Error())
		return false
	} else if response.StatusCode != 200 {
		println("response error")
		return false
	}

	// 解析回复
	responseBody, _ := ioutil.ReadAll(response.Body)
	err = json.Unmarshal(responseBody, &responseObject)
	if err != nil {
		println("response unmarshal error")
	}

	return responseObject.Res
}